<template>
  <canvas ref="canvas" class="particle-canvas"></canvas>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const canvas = ref(null)
let animationFrameId
let particles = []
let ctx, width, height

function initParticles() {
  ctx = canvas.value.getContext('2d')
  width = canvas.value.width = window.innerWidth
  height = canvas.value.height = window.innerHeight

  // 初始化粒子数组
  createParticles(100)

  window.addEventListener('resize', resizeCanvas)
  animate()
}

function createParticles(num) {
  particles = []
  for (let i = 0; i < num; i++) {
    particles.push({
      x: Math.random() * window.innerWidth,
      y: Math.random() * window.innerHeight,
      vx: (Math.random() - 0.5) * 1.5,
      vy: (Math.random() - 0.5) * 1.5,
      radius: Math.random() * 2 + 1
    })
  }
}

function resizeCanvas() {
  width = canvas.value.width = window.innerWidth
  height = canvas.value.height = window.innerHeight
}

function animate() {
  ctx.clearRect(0, 0, width, height)
  particles.forEach(p => {
    // 更新位置
    p.x += p.vx
    p.y += p.vy

    // 边界碰撞反弹
    if (p.x < 0 || p.x > width) p.vx *= -1
    if (p.y < 0 || p.y > height) p.vy *= -1

    // 绘制粒子
    ctx.beginPath()
    ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2)
    ctx.fillStyle = 'rgba(255, 255, 255, 0.7)'
    ctx.fill()
  })
  animationFrameId = requestAnimationFrame(animate)
}

onMounted(() => {
  initParticles()
})

onBeforeUnmount(() => {
  cancelAnimationFrame(animationFrameId)
  window.removeEventListener('resize', resizeCanvas)
})
</script>

<style scoped>
.particle-canvas {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none; /* 允许页面其他元素交互 */
  z-index: -1;
}
</style> 